from pptx.util import Inches, Pt
import util,math,sys
from pptx.dml.color import RGBColor
from PIL import Image
import pandas as pd
import numpy as np
from io import BytesIO
from pptx.oxml.ns import nsdecls
from pptx.oxml import parse_xml

slide = None
top_margin = 0.6
left_margin = 0.15
batch_info_table_height = 2


def create_layout_ppt(prs,batch,title):
    global slide
    slide_width = prs.slide_width/914400
    slide_height = prs.slide_height/914400
    #判断slide 是否为空
    if slide is None:
        slide = prs.slides.add_slide(prs.slide_layouts[6])
    if title == "批次信息":
        batch_info(prs,batch,title)
    if title == "Online Check":
        online_check(prs,batch,title)



def batch_info(prs,batch,title):
    left_margin = Inches(0.15)
    top_margin = Inches(0.6)
    slide_width = prs.slide_width/914400
    slide_height = prs.slide_height/914400
    util.add_text_box(slide,0,0,prs.slide_width,Inches(0.25),title,18,True)
    if len(batch)==0:
        return
    batch_pd = pd.DataFrame(batch)
    #删除所有空行
    batch_pd = batch_pd.dropna(axis=0,how='all')
    #删除所有空列
    batch_pd = batch_pd.dropna(axis=1,how='all')
    batch_pd = batch_pd.iloc[1:].reset_index(drop=True)
    batch_pd = batch_pd.iloc[:8].reset_index(drop=True)
    rows,cols = batch_pd.shape
    table_width = Inches(slide_width)-left_margin*2
    table_height = Inches(batch_info_table_height)
    table = slide.shapes.add_table(rows, cols, left_margin, top_margin, table_width, table_height).table
    #表格添加边框
    util.set_table_border(table,width=Pt(1))
    for row in range(rows):
        if row==0:
            table.rows[0].height = Inches(0.01)
        else:
            table.rows[0].height = Inches(0.1)
        for col in range(cols):
            cell = table.cell(row, col)
            val = batch_pd.iat[row, col]
            cell.text = str(val)
            cell.fill.solid()
            cell.fill.fore_color.rgb = RGBColor(255, 255, 255)
            if row==0:
                cell.fill.solid()
                cell.fill.fore_color.rgb = RGBColor(255, 165, 50)
        util.set_table_row_font_size(table,row,10)

def online_check(prs,batch,title):
    if len(batch)==0:
        return
    global slide
    title_height = 0.6
    my_top_margin = top_margin+batch_info_table_height
    util.add_text_box(slide,Inches(0),Inches(my_top_margin),prs.slide_width,Inches(title_height),title,18,True)
    #获取画布宽高
    slide_height = util.get_slide_height(slide)
    slide_width = util.get_slide_width(slide)
    batch_pd = pd.DataFrame(batch)
    #删除所有空列
    batch_pd = batch_pd.dropna(axis=1,how='all')
    #获取第一行作为标题
    #title = batch_pd.iloc[0].reset_index(drop=True)[0]
    is_bytesio = batch_pd.map(lambda x: isinstance(x, BytesIO))
    #只保留有BytesIO的行
    batch_pd = batch_pd[is_bytesio.any(axis=1)].reset_index(drop=True)
    #删除第一列
    batch_pd = batch_pd.drop(batch_pd.columns[0], axis=1)
    # 删除全是nan的行
    batch_pd = batch_pd.dropna(axis=0,how='all')
    rows,cols = batch_pd.shape
    #增加一行作为标题
    table_top = Inches(my_top_margin + title_height)
    table_left = Inches(0)
    table_width = Inches(slide_width)
    table_height = Inches(7.5-title_height-my_top_margin)
    table = slide.shapes.add_table(rows, cols, table_left, table_top, table_width, table_height).table
    #util.set_table_background(table)
    cell_width_in = table_width.inches / cols
    cell_height_in = table_height.inches / (rows+1)
    dpi = 72
    # 数据
    for row in range(rows):
        for col in range(cols):
            cell = table.cell(row, col)
            cell.fill.solid()
            cell.fill.fore_color.rgb = RGBColor(255, 255, 255)   # 设置为白色（透明填充）
            val = batch_pd.iat[row, col]
            if not isinstance(val, BytesIO):
                continue
            img_stream = val
            #重置流位置
            img_stream.seek(0)
            #打开图片
            img = Image.open(img_stream)
            img_width_px, img_height_px = img.size
            # 计算缩放比例
            cell_width_px = cell_width_in * dpi
            cell_height_px = cell_height_in * dpi
            scale = min(cell_width_px / img_width_px, cell_height_px / img_height_px, 1.0)
            img_width_in = (img_width_px * scale) / dpi*0.86
            img_height_in = (img_height_px * scale) / dpi*0.86
            pic_left = table_left.inches + (cell_width_in * col)+ (cell_width_in - img_width_in) / 2
            pic_top = table_top.inches + cell_height_in * (row) + (cell_height_in - img_height_in) / 2
            slide.shapes.add_picture(img_stream, Inches(pic_left), Inches(pic_top),width=Inches(img_width_in), height=Inches(img_height_in))
            continue